<template>
  <div class="layout-container">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ collapsed: isCollapsed }">
      <div class="logo">
        <h2 v-if="!isCollapsed">医院后台管理系统</h2>
        <div v-else class="logo-mini">医</div>
      </div>

      <!-- 菜单加载状态 -->
      <div v-if="isLoadingUserInfo" class="menu-skeleton">
        <div class="skeleton-item" v-for="i in 5" :key="i">
          <div class="skeleton-line"></div>
        </div>
      </div>

      <!-- 正常菜单 -->
      <el-menu
        v-else
        :default-active="activeMenu"
        class="sidebar-menu"
        :collapse="isCollapsed"
        :unique-opened="true"
        background-color="#001529"
        text-color="#fff"
        active-text-color="#2e6cf4"
        router
      >
        <template v-for="route in menuRoutes">
          <!-- 如果有多个子路由，显示为子菜单 -->
          <el-sub-menu
            v-if="route.children && route.children.length > 1"
            :key="`submenu-${route.path}`"
            :index="route.path"
          >
            <template #title>
              <el-icon><component :is="route.meta?.icon || 'Menu'" /></el-icon>
              <span>{{ route.meta?.title }}</span>
            </template>
            <el-menu-item
              v-for="child in route.children"
              :key="child.path"
              :index="route.path + '/' + child.path"
            >
              <el-icon
                ><component :is="child.meta?.icon || 'Document'"
              /></el-icon>
              <span>{{ child.meta?.title }}</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 单个路由或只有一个子路由，显示为单项菜单 -->
          <el-menu-item
            v-else
            :key="`menuitem-${route.path}`"
            :index="route.path"
          >
            <el-icon><component :is="route.meta?.icon || 'Menu'" /></el-icon>
            <span>{{ route.meta?.title }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 头部 -->
      <div class="header">
        <div class="header-left">
          <el-button type="text" @click="toggleCollapse" class="collapse-btn">
            <el-icon
              ><component :is="isCollapsed ? 'Expand' : 'Fold'"
            /></el-icon>
          </el-button>

          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="item in breadcrumbItems"
              :key="item.path"
              :to="item.path"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="header-right">
          <el-button type="text" @click="showFullscreen">
            <el-icon><FullScreen /></el-icon>
          </el-button>

          <!-- 主题切换器 -->
          <ThemeSelector />

          <el-dropdown @command="handleUserCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="userInfo.avatar">
                {{ userInfo.name?.charAt(0) }}
              </el-avatar>
              <span class="username">{{ userInfo.name }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout"
                  >退出登录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区 -->
      <div class="content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import ThemeSelector from "@/components/ThemeSelector/index.vue";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const isCollapsed = ref(false);
const isLoadingUserInfo = ref(false);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 如果已经有用户信息，不重复获取
    if (userStore.userInfo && userStore.userInfo.permissions.length > 0) {
      return;
    }

    isLoadingUserInfo.value = true;

    // 模拟从后端获取用户信息（这里应该调用获取当前用户信息的API）
    // 由于我们没有专门的获取用户信息API，这里根据token解析用户ID
    const token = userStore.accessToken;
    if (!token) {
      isLoadingUserInfo.value = false;
      return;
    }

    // 获取用户完整信息、角色和权限
    try {
      // 首先获取当前用户信息（不依赖Token解析）
      const userResponse = await request({
        url: `/jjx/user/current`,
        method: "GET",
      });

      if (userResponse.success && userResponse.data && userResponse.data._id) {
        const userId = userResponse.data._id;
        // 并行获取角色和权限
        const [rolesResponse, permissionsResponse] = await Promise.all([
          request({ url: `/jjx/users/${userId}/roles`, method: "GET" }),
          request({ url: `/jjx/users/${userId}/permissions`, method: "GET" }),
        ]);

        if (rolesResponse.success && permissionsResponse.success) {
          // 更新用户信息
          const userInfo = {
            id: userId,
            username:
              userResponse.data.username || userResponse.data.name || "用户",
            name:
              userResponse.data.username || userResponse.data.name || "用户",
            email: userResponse.data.email || "",
            role: rolesResponse.data?.[0]?.code || "admin",
            roles: rolesResponse.data || [],
            permissions: permissionsResponse.data || [],
          };

          userStore.setUserInfo(userInfo);
        }
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  } finally {
    isLoadingUserInfo.value = false;
  }
};

// 从store获取用户信息
const userInfo = computed(() => {
  return (
    userStore.userInfo || {
      name: "管理员",
      avatar: "",
      role: "admin",
    }
  );
});

// 计算属性
const activeMenu = computed(() => {
  return route.path;
});

// 检查路由权限
const hasRoutePermission = (route: any) => {
  // 如果路由不需要权限检查，直接显示
  if (!route.meta?.requiresAuth || !route.meta?.permission) {
    return true;
  }

  // 如果用户信息不存在，不显示需要权限的菜单
  if (!userStore.userInfo) {
    return false;
  }

  // 超级管理员拥有所有权限
  if (userStore.isSuperAdmin) {
    return true;
  }

  // 检查是否有对应权限
  return userStore.hasPermission(route.meta.permission);
};

// 获取有权限的菜单路由
const menuRoutes = computed(() => {
  // 获取根路由下的子路由作为菜单项
  const rootRoute = router.getRoutes().find((route) => route.path === "/");
  const allRoutes = router.getRoutes();

  // 收集所有有效的菜单路由
  const validRoutes = allRoutes.filter(
    (route) => route.path !== "/login" && route.meta?.hideInMenu !== true
  );

  // 如果根路由存在且有子路由，将子路由提取出来作为顶级菜单
  const menuItems: any[] = [];

  if (rootRoute && rootRoute.children) {
    rootRoute.children.forEach((child) => {
      if (child.meta && !child.meta.hideInMenu && hasRoutePermission(child)) {
        menuItems.push({
          ...child,
          path: `/${child.path}`, // 确保路径正确
        });
      }
    });
  }

  // 添加其他顶级路由（如医生管理、患者管理等）
  validRoutes.forEach((route) => {
    if (route.path !== "/" && route.children?.length) {
      // 检查路由权限
      if (hasRoutePermission(route)) {
        // 过滤子路由，只显示有权限的子路由
        const filteredChildren = route.children?.filter((child: any) =>
          hasRoutePermission(child)
        );

        // 如果有可访问的子路由，才显示父级菜单
        if (filteredChildren && filteredChildren.length > 0) {
          menuItems.push({
            ...route,
            children: filteredChildren,
          });
        }
      }
    }
  });

  return menuItems;
});

// 面包屑导航
const breadcrumbItems = computed(() => {
  const matched = route.matched.filter((item) => item.meta && item.meta.title);
  const items = matched.map((item) => ({
    path: item.path,
    title: item.meta?.title as string,
  }));

  // 过滤掉首页，如果当前就在首页则不显示面包屑
  const filteredItems = items.filter((item) => item.title !== "首页");

  // 如果当前路径是首页，返回空数组
  if (route.path === "/home") {
    return [];
  }

  return filteredItems;
});

// 方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

const showFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen();
  } else {
    document.documentElement.requestFullscreen();
  }
};

const handleUserCommand = (command: string) => {
  switch (command) {
    case "profile":
      // 跳转到个人资料页
      break;
    case "password":
      // 显示修改密码对话框
      break;
    case "logout":
      logout();
      break;
  }
};

const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 使用store的logout方法清除双token
      userStore.logout();
      ElMessage.success("退出登录成功");
      router.push("/login");
    })
    .catch(() => {
      // 用户取消退出
    });
};

// 监听路由变化，更新标题
watch(
  () => route.meta.title,
  (title) => {
    if (title) {
      document.title = `${title} - 互联网医院管理平台`;
    }
  },
  { immediate: true }
);

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<style lang="scss" scoped>
.layout-container {
  display: flex;
  height: 100vh;

  .sidebar {
    width: 200px;
    background: var(--theme-sidebar-bg, #001529);
    transition: width 0.2s, background-color 0.3s ease;
    display: flex;
    flex-direction: column;
    border-right: 1px solid var(--el-border-color-light, #e4e7ed);

    &.collapsed {
      width: 64px;
    }

    .logo {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 16px;
      border-bottom: 1px solid var(--el-border-color, #dcdfe6);
      background: var(--theme-sidebar-bg, #001529);

      img {
        height: 32px;
        margin-right: 8px;
      }

      h2 {
        color: var(--theme-sidebar-text, #fff);
        font-size: 18px;
        margin: 0;
        white-space: nowrap;
      }

      .logo-mini {
        color: var(--theme-sidebar-text, #fff);
        font-size: 20px;
        font-weight: bold;
      }
    }

    .sidebar-menu {
      flex: 1;
      border: none;
      background-color: var(--theme-sidebar-bg, #001529);

      :deep(.el-menu-item),
      :deep(.el-sub-menu__title) {
        color: var(--theme-sidebar-text, #fff) !important;

        &:hover {
          background-color: var(--theme-sidebar-hover-bg, #1f2937) !important;
          color: var(--theme-menu-active-color, #409eff) !important;
        }

        .el-icon {
          color: var(--theme-sidebar-text, #fff) !important;
        }
      }

      :deep(.el-menu-item.is-active) {
        background-color: var(--theme-menu-active-bg, #2e6cf4) !important;
        color: var(--theme-menu-active-color, #ffffff) !important;

        .el-icon {
          color: var(--theme-menu-active-color, #ffffff) !important;
        }
      }

      :deep(.el-sub-menu .el-menu) {
        background-color: var(--el-fill-color-light, #1f2937);
      }
    }
  }

  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .header {
      height: 60px;
      background: var(--theme-header-bg, #fff);
      border-bottom: 1px solid var(--theme-header-border, #f0f0f0);
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24px;
      transition: background-color 0.3s ease, border-color 0.3s ease;

      .header-left {
        display: flex;
        align-items: center;

        .collapse-btn {
          margin-right: 16px;
          font-size: 18px;
          color: var(--theme-header-text, #303133);

          &:hover {
            color: var(--el-color-primary, #409eff);
          }
        }

        :deep(.el-breadcrumb) {
          .el-breadcrumb__item {
            .el-breadcrumb__inner {
              color: var(--el-text-color-secondary, #909399);

              &:hover {
                color: var(--el-color-primary, #409eff);
              }
            }
          }

          .el-breadcrumb__separator {
            color: var(--el-text-color-placeholder, #a8abb2);
          }
        }
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 16px;

        .user-info {
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          padding: 8px;
          border-radius: 4px;
          transition: background-color 0.2s;
          color: var(--theme-header-text, #303133);

          &:hover {
            background-color: var(--el-fill-color, #f5f5f5);
          }

          .username {
            font-size: 14px;
          }
        }

        :deep(.el-button--text) {
          color: var(--theme-header-text, #303133);

          &:hover {
            color: var(--el-color-primary, #409eff);
          }
        }
      }
    }

    .content {
      flex: 1;
      padding: 24px;
      background: var(--el-bg-color-page, #f5f5f5);
      overflow-y: auto;
      transition: background-color 0.3s ease;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .layout-container {
    .sidebar {
      position: fixed;
      left: -200px;
      z-index: 1000;
      height: 100vh;

      &.mobile-show {
        left: 0;
      }
    }

    .main-content {
      width: 100%;
    }
  }

  // 菜单骨架屏样式
  .menu-skeleton {
    padding: 12px;

    .skeleton-item {
      margin-bottom: 16px;

      .skeleton-line {
        height: 40px;
        background: linear-gradient(
          90deg,
          #1f2937 25%,
          #374151 50%,
          #1f2937 75%
        );
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
        border-radius: 4px;
      }
    }
  }

  @keyframes skeleton-loading {
    0% {
      background-position: 200% 0;
    }
    100% {
      background-position: -200% 0;
    }
  }
}
</style>